package com.yuexin.project.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuexin.common.exception.user.UserNotFoundException;
import com.yuexin.common.utils.QRCodeUtil;
import com.yuexin.common.utils.StringUtils;
import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.framework.web.controller.BaseController;
import com.yuexin.framework.web.domain.AjaxResult;
import com.yuexin.project.abutment.domain.Company;
import com.yuexin.project.abutment.mapper.AbutmentMapper;
import com.yuexin.project.dailymenu.dishlist.domain.DishList;
import com.yuexin.project.dailymenu.dishlist.mapper.DishListMapper;
import com.yuexin.project.dailymenu.dishtype.domain.DishType;
import com.yuexin.project.dailymenu.dishtype.mapper.TypeMapper;
import com.yuexin.project.dailymenu.everyday.domain.DailyMenuDish;
import com.yuexin.project.dailymenu.everyday.domain.EverydayMenu;
import com.yuexin.project.dailymenu.everyday.mapper.EveryDayMenuDishMapper;
import com.yuexin.project.dailymenu.everyday.mapper.EverydayMenuMapper;
import com.yuexin.project.dailymenu.menumanager.domain.Manager;
import com.yuexin.project.dailymenu.menumanager.mapper.ManagerMapper;
import com.yuexin.project.finance.bill.domain.Bill;
import com.yuexin.project.finance.bill.service.IBillService;
import com.yuexin.project.mobile.formbean.*;
import com.yuexin.project.order.domain.GuestUser;
import com.yuexin.project.order.domain.MealsSetting;
import com.yuexin.project.order.domain.PeriUser;
import com.yuexin.project.order.mapper.GuestUserMapper;
import com.yuexin.project.order.mapper.MealsSettingMapper;
import com.yuexin.project.order.mapper.PeriUserMapper;
import com.yuexin.project.statistic.aroundDinner.domain.AroundDinner;
import com.yuexin.project.statistic.aroundDinner.mapper.AroundDinnerMapper;
import com.yuexin.project.statistic.book.domain.Book;
import com.yuexin.project.statistic.book.formbean.MaxSortFormBean;
import com.yuexin.project.statistic.book.mapper.BookMapper;
import com.yuexin.project.statistic.bookDish.domain.BookDish;
import com.yuexin.project.statistic.bookDish.service.IBookDishService;
import com.yuexin.project.system.notice.domain.Notice;
import com.yuexin.project.system.notice.service.INoticeService;
import com.yuexin.project.system.user.domain.User;
import com.yuexin.project.system.user.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.codec.binary.Base64;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 每日菜单 移动端接口
 *
 * @author yuexin
 * @date 2018-10-14
 */
@Api("手机端管理")
@RestController
@RequestMapping("/meals/mobile")
public class MealsForMobileAPIController extends BaseController {
    @Autowired
    private EverydayMenuMapper everydayMenuMapper;
    @Autowired
    private EveryDayMenuDishMapper everydayMenuDishMapper;
    @Autowired
    private DishListMapper dishListMapper;
    @Autowired
    private TypeMapper dishTypeMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private AroundDinnerMapper aroundMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private MealsSettingMapper mealsSettingMapper;
    @Autowired
    private GuestUserMapper guestUserMapper;
    @Autowired
    private PeriUserMapper periUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AbutmentMapper abutmentMapper;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IBookDishService bookDishService;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private IBillService billService;


    /**
     * 查询每日菜单列表
     */
    @PostMapping("/getDailyMenuByDate")
    @ApiOperation("查询每日菜单列表")
    public Result getDailyMenuByDate(String dailyInfo) {
        JSONObject jobj = JSON.parseObject(dailyInfo);
        JSONObject data = jobj.getJSONObject("data");
        MealsListFormBean form = JSON.toJavaObject(data, MealsListFormBean.class);
        EverydayMenu everydayMenu = new EverydayMenu();
        everydayMenu.setCompanyId(form.getToken().getCompanyId());
        everydayMenu.setDailyDate(form.getMenuDate());
        // 每日排餐菜单
        EverydayMenu everydayMenuBean = everydayMenuMapper.selectEverydayMenuByDailyDate(everydayMenu);
        if (everydayMenuBean == null) {
            return new Result(ResultCode.WARN);
        }
        Integer dailyId = everydayMenuBean.getDailyId();
        List<DailyMenuDish> dailyMenuDishs = Lists.newArrayList();
        // 当前报餐设置
        MealsSetting setting = getMealsSetting(form.getToken().getCompanyId());
        // 获取报餐明细
        List<Book> bookList = getMealsInfoList(dailyInfo, StringUtils.isNotEmpty(form.getDinnerType()) ? "1" : "0");
        List<Integer> bookIds = Lists.newArrayList();
        // 获取报餐ID
        if (bookList != null && !bookList.isEmpty()) {
            bookList.stream().forEach(item -> bookIds.add(item.getBookId()));
        }
        // 获取报餐菜品明细
        List<BookDish> bookDishes = bookIds != null && !bookIds.isEmpty() ? bookDishService.selectBookDishByBookId(bookIds) : Lists.newArrayList();
        everydayMenuDishMapper.selectEverydayMenuDishListByDailyId(dailyId).stream().forEach(item -> {
            if (StringUtils.isNotEmpty(form.getDinnerType()) && !form.getDinnerType().equals(item.getDinnerType())) {
                return;
            }
            DishList dishList = dishListMapper.selectListById(item.getDishId());
            if (dishList == null) {
                return;
            }
            item.setDishName(dishList.getDishName());
            item.setDishPic("0".equals(setting.getIsDishPic()) ? dishList.getDishPic() : "");
            // 设置累加菜品价格显示
            BigDecimal price =
                    // 早餐设置累加菜品
                    ("0".equals(item.getDinnerType()) && "1".equals(setting.getBreakfastType()) && "-1".equals(setting.getBreakfastType1())) ||
                            // 午餐设置累加菜品
                            ("1".equals(item.getDinnerType()) && "1".equals(setting.getLunchType()) && "-1".equals(setting.getLunchType1())) ||
                            // 晚餐设置累加菜品
                            ("2".equals(item.getDinnerType()) && "1".equals(setting.getDinnerType()) && "-1".equals(setting.getDinnerType1())) ||
                            // 其他餐设置累加菜品
                            ("3".equals(item.getDinnerType()) && "1".equals(setting.getOtherType()) && "-1".equals(setting.getOtherType1())) ? dishList.getDishPrice() : null;
            item.setDishPrice(price);
            int several = 0;
            for (BookDish bookDish : bookDishes) {
                if (bookDish.getDinnerType().equals(item.getDinnerType()) && bookDish.getDishId().equals(item.getDishId())) {
                    several = bookDish.getSeveral();
                    break;
                }
            }
            item.setSeveral(several);
            dailyMenuDishs.add(item);
        });
        everydayMenuBean.setEveryMenuDishs(dailyMenuDishs);
        return new Result(ResultCode.SUCCESS, everydayMenuBean);
    }

    /**
     * 获取报餐明细
     *
     * @param info
     * @param bookType
     * @return
     */
    private List<Book> getMealsInfoList(String info, String bookType) {
        JSONObject jobj = JSON.parseObject(info);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject token = (JSONObject) data.get("token");
        Book book = new Book();
        book.setUserNameMobile(token.getString("userName"));
        book.setBookType(bookType);
        book.setCompanyId(token.getString("companyId"));
        book.setBookId(data.getInteger("bookId"));
        if (data.getDate("menuDate") == null && !"1".equals(bookType)) {
            return null;
        }
        book.setEatDate(data.getDate("menuDate"));
        List<Book> bookList = bookMapper.selectBookList(book);
        return bookList;
    }

    /**
     * 获取自食报餐信息
     */
    @PostMapping("/getMealsItemForSelf")
    @ApiOperation("获取自食报餐信息")
    public Result getMealsItemForSelf(String selfInfo) {
        List<Book> bookList = getMealsInfoList(selfInfo, "0");
        return new Result(ResultCode.SUCCESS, bookList);
    }

    /**
     * 新增自食报餐条目
     */
    @PostMapping("/addMealsItemForSelf")
    @ApiOperation("新增自食报餐条目")
    @Transactional
    public Result addMealsItem(String json) {
        JSONObject data = (JSONObject) JSON.parseObject(json).get("data");
        AddBookFormBean form = JSON.toJavaObject(data, AddBookFormBean.class);
        List<String> bookIds = Lists.newArrayList();
        form.getCallMeal().stream().forEach(item -> bookIds.add(item.getBookId()));
        deleteByBookId(bookIds);
        User user = userMapper.selectUserByLoginName(form.getToken().getUserName());
        // 报餐报餐ID【key：报餐类别（0:早,1:中,2:晚,3:其他），value：报餐ID】
        Map<String, Integer> bookIdMap = Maps.newHashMap();
        List<Integer> bookIdList = Lists.newArrayList();
        form.getCallMeal().stream().forEach(item -> {
            if (StringUtils.isEmpty(item.getDinnerType())) {
                return;
            }
            Book book = modelMapper.map(item, Book.class);
            book.setUserName(form.getToken().getUserName());
            book.setBookType("0");
            book.setUserId(user.getUserId());
            book.setCompanyId(form.getToken().getCompanyId());
            book.setCreateTime(new Date());
            book.setCreateBy(form.getToken().getUserName());
            bookMapper.insertBook(book);
            bookIdList.add(book.getBookId());
            bookIdMap.put(item.getDinnerType(), book.getBookId());
        });
        if(form.getBookDishes() != null && !form.getBookDishes().isEmpty()){
            // 批量新增报餐菜品明细
            batchAddBookDish(form.getBookDishes(), form.getToken(), bookIdMap);
        }
        return new Result(ResultCode.SUCCESS, bookIdList);
    }

    /**
     * 批量新增报餐菜品明细
     *
     * @param bookDishs
     * @param token
     * @param bookIdMap
     */
    private void batchAddBookDish(List<BookDishFormBean> bookDishs, TokenFormBean token, Map<String, Integer> bookIdMap) {
        List<BookDish> bookDishData = setBatchAddBookDishEntity(bookDishs, token, bookIdMap);
        if (bookDishData == null || bookDishData.isEmpty()) {
            return;
        }
        bookDishService.batchInsertBookDish(bookDishData);
    }

    /**
     * 设置报餐菜品明细
     *
     * @param bookDishs
     * @param token
     * @param bookIdMap
     */
    private List<BookDish> setBatchAddBookDishEntity(List<BookDishFormBean> bookDishs, TokenFormBean token, Map<String, Integer> bookIdMap) {
        List<BookDish> bookDishData = Lists.newArrayList();
        for (BookDishFormBean item : bookDishs) {
            BookDish bookDish = modelMapper.map(item, BookDish.class);
            bookDish.setCompanyId(token.getCompanyId());
            bookDish.setUserName(token.getUserName());
            bookDish.setBookId(bookIdMap.get(item.getDinnerType()));
            bookDish.setCreateBy(token.getUserName());
            bookDish.setCreateTime(new Date());
            bookDishData.add(bookDish);
        }
        return bookDishData;
    }

    /**
     * 删除自食报餐条目
     */
    @PostMapping("/delMealsItemForSelf")
    @ApiOperation("删除自食报餐条目")
    @Transactional
    public Result delMealsItemForSelf(String json) {
        delBook(json);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 删除报餐以及报餐菜品明细
     *
     * @param json
     * @return
     */
    private int delBook(String json) {
        JSONObject jobj = JSON.parseObject(json);
        JSONObject data = (JSONObject) jobj.get("data");
        String bookId = data.getString("bookId");
        return deleteByBookId(Lists.newArrayList(bookId));
    }

    /**
     * 根据ID删除
     *
     * @param bookIds
     * @return
     */
    private int deleteByBookId(List<String> bookIds) {
        bookMapper.deleteBookByIds(bookIds);
        return deleBookDish(bookIds);
    }

    /**
     * 删除报餐菜品明细
     *
     * @param bookIds
     * @return
     */
    private int deleBookDish(List<String> bookIds) {
        return bookDishService.deleteBookDishByBookIds(bookIds);
    }

    /**
     * 获取客餐报餐信息
     */
    @GetMapping("/getMealsInfoForGuest")
    @ApiOperation("获取客餐报餐信息")
    public Result getMealsInfoForGuest(String guestInfo) {
        List<Book> bookList = getMealsInfoList(guestInfo, "1");
        return new Result(ResultCode.SUCCESS, bookList);
    }

    /**
     * 新增客餐报餐信息
     */
    @PostMapping("/addMealsInfoForGuest")
    @ApiOperation("新增客餐报餐信息")
    @Transactional
    public Result addMealsInfoForGuest(String guestInfo) {
        JSONObject data = (JSONObject) JSON.parseObject(guestInfo).get("data");
        AddBookForGuestFormBean form = JSON.toJavaObject(data, AddBookForGuestFormBean.class);
        User user = userMapper.selectUserByLoginName(form.getToken().getUserName());
        Book book = modelMapper.map(form.getCallMeal(), Book.class);
        book.setUserName(form.getToken().getUserName());
        book.setBookType("1");
        book.setCompanyId(form.getToken().getCompanyId());
        book.setUserId(user.getUserId());
        bookMapper.insertBook(book);
        // 批量新增报餐菜品明细
        addBookDishForGuest(form, book.getBookId());
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 批量新增报餐菜品明细
     *
     * @param form
     * @param bookId
     */
    private void addBookDishForGuest(AddBookForGuestFormBean form, Integer bookId) {
        // 批量新增报餐菜品明细
        List<BookDish> bookDishData = Lists.newArrayList();
        for (BookDishFormBean item : form.getBookDishes()) {
            BookDish bookDish = modelMapper.map(item, BookDish.class);
            bookDish.setCompanyId(form.getToken().getCompanyId());
            bookDish.setUserName(form.getToken().getUserName());
            bookDish.setBookId(bookId);
            bookDish.setCreateBy(form.getToken().getUserName());
            bookDish.setCreateTime(new Date());
            bookDishData.add(bookDish);
        }
        bookDishService.batchInsertBookDish(bookDishData);
    }

    /**
     * 修改客餐报餐信息
     */
    @PostMapping("/updateMealsInfoForGuest")
    @ApiOperation("修改客餐报餐信息")
    public Result updateMealsInfoForGuest(String guestInfo) {
        JSONObject data = (JSONObject) JSON.parseObject(guestInfo).get("data");
        AddBookForGuestFormBean form = JSON.toJavaObject(data, AddBookForGuestFormBean.class);
        Book book = modelMapper.map(form.getCallMeal(), Book.class);
        book.setUserName(form.getToken().getUserName());
        book.setBookType("1");
        book.setCompanyId(form.getToken().getCompanyId());
        bookMapper.updateBook(book);
        // 删除报餐菜品明细
        deleBookDish(Lists.newArrayList(book.getBookId().toString()));
        // 新增报餐菜品明细
        addBookDishForGuest(form, book.getBookId());
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 删除客餐报餐信息
     */
    @PostMapping("/deleteMealsInfoForGuest")
    @ApiOperation("删除客餐报餐信息")
    @Transactional
    public Result deleteMealsInfoForGuest(String guestInfo) {
        delBook(guestInfo);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 获取围餐报餐信息
     */
    @GetMapping("/getMealsInfoForPeri")
    @ApiOperation("获取围餐报餐信息")
    public Result getMealsInfoForPeri(String periInfo) {
        JSONObject jobj = JSON.parseObject(periInfo);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject token = (JSONObject) data.get("token");
        //String orgId = token.getString("oaOrgId");
        String companyId = token.getString("companyId");

        AroundDinner aroundDinner = new AroundDinner();
        //aroundDinner.setUserName(token.getString("userName"));
        aroundDinner.setUserNameMobile(token.getString("userName"));
        aroundDinner.setCompanyId(companyId);
        List<AroundDinner> arounds = aroundMapper.selectAroundDinnerList(aroundDinner);
        return new Result(ResultCode.SUCCESS, arounds);
    }

    /**
     * 获取围餐菜单信息
     */
    @GetMapping("/getPeriMenuInfo")
    @ApiOperation("获取围餐菜单信息")
    public Result getPeriMenuInfo(String info) {
        JSONObject jobj = JSON.parseObject(info);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject token = (JSONObject) data.get("token");
        //String orgId = token.getString("oaOrgId");
        String companyId = token.getString("companyId");

        List<Manager> periMenuList = new ArrayList<Manager>();
        List<Manager> menuList = managerMapper.selectMenuAll(companyId);
        for (Manager manager : menuList) {
            String menuType = manager.getMenuType();
            if ("1".equals(menuType)) {
                Integer menuId = manager.getMenuId();
                List<String> dishList = dishListMapper.selectMenuDishListByMenuId(menuId);
                manager.setDishList(dishList);
                periMenuList.add(manager);
            }
        }
        return new Result(ResultCode.SUCCESS, periMenuList);
    }

    /**
     * 获取菜品类别信息
     */
    @GetMapping("/getDishTypeInfo")
    @ApiOperation("获取菜品类别信息")
    public Result getDishTypeInfo(String info) {
        JSONObject jobj = JSON.parseObject(info);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject token = (JSONObject) data.get("token");
        String companyId = token.getString("companyId");
        List<DishType> typeList = dishTypeMapper.selectDishTypeAll(companyId);
        return new Result(ResultCode.SUCCESS, typeList);
    }

    /**
     * 获取菜品列表信息
     */
    @GetMapping("/getDishListInfo")
    @ApiOperation("获取菜品列表信息")
    public Result getDishListInfo(String info) {
        JSONObject jobj = JSON.parseObject(info);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject token = (JSONObject) data.get("token");
        //String orgId = token.getString("oaOrgId");
        String companyId = token.getString("companyId");
        List<DishList> dishList = dishListMapper.selectDishListAll(companyId);
        return new Result(ResultCode.SUCCESS, dishList);
    }

    /**
     * 新增围餐报餐信息
     */
    @PostMapping("/addMealsInfoForPeri")
    @ApiOperation("新增围餐报餐信息")
    public Result addMealsInfoForPeri(String periInfo) {
        JSONObject jobj = JSON.parseObject(periInfo);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject periMeals = (JSONObject) data.get("periMeals");
        JSONObject token = (JSONObject) data.get("token");
        //String orgId = token.getString("oaOrgId");
        String companyId = token.getString("companyId");
        AroundDinner aroundDinner = new AroundDinner();
        aroundDinner.setUserName(token.getString("userName"));
        aroundDinner.setAroundDate(periMeals.getDate("aroundDate"));
        aroundDinner.setAroundType(periMeals.getString("aroundType"));
        aroundDinner.setAroundCount(periMeals.getString("aroundCount"));
        aroundDinner.setAroundPersion(periMeals.getString("aroundPersion"));
        aroundDinner.setAroundOtherReq(periMeals.getString("aroundOtherReq"));
        aroundDinner.setAroundReq(periMeals.getString("aroundReq"));
        aroundDinner.setCompanyId(companyId);
        aroundMapper.insertAroundDinner(aroundDinner);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 修改围餐报餐信息
     */
    @PostMapping("/updateMealsInfoForPeri")
    @ApiOperation("修改围餐报餐信息")
    public Result updateMealsInfoForPeri(String periInfo) {
        JSONObject jobj = JSON.parseObject(periInfo);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject periMeals = (JSONObject) data.get("periMeals");
        JSONObject token = (JSONObject) data.get("token");
        AroundDinner aroundDinner = new AroundDinner();
        aroundDinner.setAroundId(periMeals.getInteger("aroundId"));
        aroundDinner.setUserName(token.getString("userName"));
        aroundDinner.setAroundDate(periMeals.getDate("aroundDate"));
        aroundDinner.setAroundType(periMeals.getString("aroundType"));
        aroundDinner.setAroundCount(periMeals.getString("aroundCount"));
        aroundDinner.setAroundPersion(periMeals.getString("aroundPersion"));
        aroundDinner.setAroundOtherReq(periMeals.getString("aroundOtherReq"));
        aroundDinner.setAroundReq(periMeals.getString("aroundReq"));
        aroundMapper.updateAroundDinner(aroundDinner);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 删除围餐报餐信息
     */
    @PostMapping("/deleteMealsInfoForPeri")
    @ApiOperation("删除围餐报餐信息")
    public Result deleteMealsInfoForPeri(String periInfo) {
        JSONObject jobj = JSON.parseObject(periInfo);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject periMeals = (JSONObject) data.get("periMeals");

        Integer aroundId = periMeals.getInteger("aroundId");
        aroundMapper.deleteAroundDinnerById(aroundId);
        return new Result(ResultCode.SUCCESS);
    }

    private Integer getDays(Integer year, Integer month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0); //输入类型为int类型
        return c.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取批量报餐信息
     * {"data":{"token":{},"meal":{"year":2018,"month":10}}}
     */
    @GetMapping("/getMealsInfoForBatch")
    @ApiOperation("获取批量报餐信息")
    public Result getMealsInfoForBatch(String mealsInfo) {
        JSONObject jobj = JSON.parseObject(mealsInfo);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject meal = (JSONObject) data.get("meal");
        JSONObject token = (JSONObject) data.get("token");
        String companyId = token.getString("companyId");
        String userName = token.getString("userName");
        Integer year = (Integer) meal.get("year");
        Integer month = (Integer) meal.get("month");

        Integer days = getDays(year, month);
        Book book = new Book();
        book.setUserNameMobile(userName);
        Map<String, Object> params = Maps.newHashMap();
        params.put("beginTime", year + "-" + month + "-" + 01);
        params.put("endTime", year + "-" + month + "-" + days);
        book.setParams(params);
        book.setCompanyId(companyId);
        List<Book> bookList = bookMapper.selectBookList(book);

        //根据月份获取每日开餐信息
        EverydayMenu everydayMenu = new EverydayMenu();
        everydayMenu.setParams(params);
        everydayMenu.setCompanyId(companyId);
        List<EverydayMenu> everyDayMenuList = everydayMenuMapper.selectEverydayMenuList(everydayMenu);

        Map<String, Object> result = Maps.newHashMap();
        result.put("bookList", bookList);
        result.put("everydayMenuList", everyDayMenuList);
        return new Result(ResultCode.SUCCESS, result);
    }

    /**
     * 新增批量报餐信息
     */
    @PostMapping("/addMealsInfoForBatch")
    @ApiOperation("新增批量报餐信息")
    public Result addMealsInfoForBatch(String json) {
        JSONObject jobj = JSON.parseObject(json);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONArray array = (JSONArray) data.get("callMeal");
        JSONObject token = (JSONObject) data.get("token");
        String companyId = token.getString("companyId");
        Integer year = (Integer) data.get("year");
        Integer month = (Integer) data.get("month");
        String dinnerType = data.getString("dinnerType");
        BigDecimal totalPrice = data.getBigDecimal("totalPrice");

        //先删除已报餐
        Book bookDel = new Book();
        String userName = token.getString("userName");
        Integer days = getDays(year, month);
        bookDel.setUserName(userName);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("beginTime", year + "-" + month + "-" + 01);
        params.put("endTime", year + "-" + month + "-" + days);
        bookDel.setParams(params);
        bookDel.setDinnerType(dinnerType);
        bookDel.setBookType("0");
        bookDel.setCompanyId(companyId);
        bookMapper.deleteBookByMonth(bookDel);

        //插入报餐数据
        List<Book> bookList = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            Book book = new Book();
            JSONObject job = array.getJSONObject(i);
            book.setUserName(token.getString("userName"));
            book.setDinnerType(job.getString("dinnerType"));
            book.setBookNum(job.getInteger("bookNum"));
            book.setBookType("0");
            book.setEatDate(job.getDate("eatDate"));
            book.setCompanyId(companyId);
            book.setTotalPrice(totalPrice);
            bookList.add(book);
        }

        bookMapper.batchMealsInfo(bookList);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据扫码时间判断餐别
     *
     * @param companyId
     * @param time
     * @return
     */
    private String getDinnerType(String companyId, String time) {
        String dinnerType = "";
        MealsSetting mealsSetting = mealsSettingMapper.selectSettingByCompanyId(companyId);
        if (mealsSetting == null) {
            mealsSetting = mealsSettingMapper.selectSettingByCompanyId("dingcan");
        }
        String breakfastStart = mealsSetting.getBreakfastStart();
        String breakfastEnd = mealsSetting.getBreakfastEnd();
        String lunchStart = mealsSetting.getLunchStart();
        String lunchEnd = mealsSetting.getLunchEnd();
        String dinnerStart = mealsSetting.getDinnerStart();
        String dinnerEnd = mealsSetting.getDinnerEnd();
        String otherStart = mealsSetting.getOtherStart();
        String otherEnd = mealsSetting.getOtherEnd();

        if (compareTime(breakfastStart, time, breakfastEnd)) {
            dinnerType = "0";
        } else if (compareTime(lunchStart, time, lunchEnd)) {
            dinnerType = "1";
        } else if (compareTime(dinnerStart, time, dinnerEnd)) {
            dinnerType = "2";
        } else if (compareTime(otherStart, time, otherEnd)) {
            dinnerType = "3";
        }
        return dinnerType;
    }

    private boolean compareTime(String start, String now, String end) {
        boolean result = false;
        DateFormat df = new SimpleDateFormat("HH:mm");//创建日期转换对象HH:mm:ss为时分秒，年月日为yyyy-MM-dd
        try {
            Date startDate = df.parse(start);//将字符串转换为date类型
            Date nowDate = df.parse(now);
            Date endDate = df.parse(end);
            if ((nowDate.getTime() >= startDate.getTime()) && (nowDate.getTime() <= endDate.getTime()))//比较时间大小
            {
                result = true;
            }
        } catch (ParseException e) {
            result = false;
        }
        return result;
    }

    /**
     * 获取扫码签到状态
     * {"data":{"token":{},"callMeal":{"bookId":1}}}
     */
    @PostMapping("/scavenging")
    @ApiOperation("获取扫码签到状态")
    public AjaxResult scavenging(String mealsInfo) {
        JSONObject jobj = JSON.parseObject(mealsInfo);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject token = (JSONObject) data.get("token");
        //String orgId = token.getString("oaOrgId");
        String companyId = token.getString("companyId");
        String userName = token.getString("userName");
        String isChange = data.getString("isChange");
        String result = data.getString("res");

        //String result = (String)data.get("token");//获取扫码返回结果

        int y, m, d, h, mi;
        Calendar cal = Calendar.getInstance();
        y = cal.get(Calendar.YEAR);
        m = cal.get(Calendar.MONTH) + 1;
        d = cal.get(Calendar.DATE);
        h = cal.get(Calendar.HOUR_OF_DAY);
        mi = cal.get(Calendar.MINUTE);
        //s=cal.get(Calendar.SECOND);

        String dinnerType = getDinnerType(companyId, h + ":" + mi);
        if (!"0".equals(dinnerType) && !"1".equals(dinnerType) && !"2".equals(dinnerType) && !"3".equals(dinnerType)) {
            //return new Result(ResultCode.WARN,"现在不是就餐时间哦！");
            return error(-1, "现在不是就餐时间哦！");
        }

        Book book = new Book();
        book.setUserNameMobile(userName);
        String eatDateString = y + "-" + m + "-" + d;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date eatDate;
        try {
            eatDate = sdf.parse(eatDateString);
            book.setEatDate(eatDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        book.setDinnerType(data.getString("dinnerType"));
        book.setCompanyId(companyId);
        List<Book> bookList = bookMapper.selectBookList(book);
        if (bookList != null && bookList.size() > 0) {
            //如果扫码成功，将签到设为已签状态
            if ("1".equals(isChange)) {
                //判断扫码是否合法

                String[] resultStrArray = result.split("\\.");
                if (resultStrArray.length >= 2) {
                    String orgid = resultStrArray[0];
                    String times = resultStrArray[1];
                    String ordidDecode = getDecodeInfo(orgid);
                    if (!"dingcanxitongorgid".equals(ordidDecode)) {
                        return error(-1, "二维码错误！请扫描食堂电脑上的动态二维码！");
                    }

                    //若获取时间和当前时间相差大于60秒则超时
                    long getScanTimes = Long.parseLong(times);
                    long currentTimes = System.currentTimeMillis();
                    Long s = (currentTimes - getScanTimes) / 1000;
                    if (s > 300) {
                        return error(-1, "二维码已过期，请重新扫码！");
                    }
                } else {
                    return error(-1, "二维码错误！请扫描食堂电脑上的动态二维码！");
                }
                int userId = Integer.parseInt(resultStrArray[2]);
                for (Book b : bookList) {
                    Integer bookId = b.getBookId();
                    book.setBookId(bookId);
                    book.setSignIn("1");
                    book.setSignTime(new Date());
                    book.setCookUserId(userId);
                    bookMapper.updateBook(book);
                }
            }
            bookList.stream().forEach(item -> item.setBookDishes(bookDishService.selectBookDishByBookId(Lists.newArrayList(item.getBookId()))));
            return success(bookList);
        } else {
            //return new Result(ResultCode.WARN,"您未报餐，不可就餐哦！");
            return error(-1, "您未报餐，不可就餐哦！");
        }
    }

    /**
     * 确认领餐
     * {"data":{"token":{},"callMeal":{"bookId":1},"totalPrice":65,"remark":"午餐3份","cookUserId":133}}
     */
    @PostMapping("/confirmGet")
    @Transactional
    @ApiOperation("确认领餐")
    public Result confirmGet(String mealsInfo) {
        JSONObject jobj = JSON.parseObject(mealsInfo);
        JSONObject data = (JSONObject) jobj.get("data");
        TokenFormBean token = JSON.parseObject(data.getString("token"), TokenFormBean.class);
        BigDecimal totalPrice = data.getBigDecimal("totalPrice");
        User user = userMapper.selectUserByLoginName(token.getUserName());
        BigDecimal money = user.getMoney() == null ? new BigDecimal(0):user.getMoney();
        if (user == null || money.compareTo(totalPrice) == -1) {
            return new Result(ResultCode.FAILURE, "余额不足");
        }
        String remark = data.getString("remark");
        Long cookUserId = data.getLong("cookUserId");
        User cooUser = userMapper.selectUserById(cookUserId);
        JSONArray array = (JSONArray) data.get("callMeal");
        Integer sort = getMaxSort(token.getCompanyId(), cookUserId);
        if(sort == null && cookUserId != null){
            sort = 0;
        }
        for (int i = 0; i < array.size(); i++) {
            Book book = new Book();
            JSONObject job = array.getJSONObject(i);
            book.setBookId(job.getInteger("bookId"));
            book.setIsEat("1");
            book.setEatTime(new Date());
            if(sort != null){
                book.setSort(sort + 1);
            }
            bookMapper.updateBook(book);
        }
        if(totalPrice == null || totalPrice.compareTo(new BigDecimal(0)) == 0){
            return new Result(ResultCode.SUCCESS);
        }
        Bill bill = new Bill();
        if(cooUser != null){
            bill.setCreateBy(cooUser.getLoginName());
        }
        bill.setCreateTime(new Date());
        bill.setCompanyId(token.getCompanyId());
        bill.setUserName(token.getUserName());
        bill.setBillType("3");
        bill.setMoney(money.subtract(totalPrice));
        bill.setPrice(totalPrice);
        bill.setRemark(remark);
        billService.insertBill(bill);
        user.setMoney(money.subtract(totalPrice));
        userMapper.updateUser(user);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 获取当前排队序号
     * @param companyId
     * @param cookUserId
     * @return
     */
    private Integer getMaxSort(String companyId, Long cookUserId) {
        MaxSortFormBean form = new MaxSortFormBean();
        form.setCompanyId(companyId);
        form.setCookUserId(cookUserId);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        form.setEatTime(df.format(new Date()));
        return bookMapper.selectMaxSort(form);
    }

    private List<String> getUserNamesGuest(List<GuestUser> guestUserList) {
        List<String> userNames = new ArrayList<String>();
        List<User> users = userMapper.selectUserAll();
        for (User user : users) {
            for (GuestUser userRole : guestUserList) {
                if (user.getUserId().longValue() == userRole.getUserId().longValue()) {
                    String loginName = user.getLoginName();
                    userNames.add(loginName);
                    break;
                }
            }
        }

        return userNames;
    }

    private List<String> getUserNamesPeri(List<PeriUser> periUserList) {
        List<String> userNames = new ArrayList<String>();
        List<User> users = userMapper.selectUserAll();
        for (User user : users) {
            for (PeriUser userRole : periUserList) {
                if (user.getUserId().longValue() == userRole.getUserId().longValue()) {
                    String userName = user.getUserName();
                    userNames.add(userName);
                    break;
                }
            }
        }

        return userNames;
    }

    /**
     * 获取报餐设置信息
     */
    @GetMapping("/getMealsSettingInfo")
    @ApiOperation("获取报餐设置信息")
    public Result getMealsSettingInfo(String info) {
        JSONObject jobj = JSON.parseObject(info);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject token = (JSONObject) data.get("token");
        String companyId = token.getString("companyId");
        String userName = token.getString("userName");
        List<GuestUser> guestUserList = guestUserMapper.selectGuestUserList();
        List<PeriUser> periUserList = periUserMapper.selectPeriUserList();
        List<Notice> notices = noticeService.selectUnreadNoticeByUserName(userName, companyId);
        // 公告通知
        Notice notice = notices != null && !notices.isEmpty() ? notices.get(0) : null;
        Map<String, Object> params = Maps.newHashMap();
        params.put("mealsSetting", getMealsSetting(companyId));
        params.put("guestUserList", getUserNamesGuest(guestUserList));
        params.put("periUserList", getUserNamesPeri(periUserList));
        params.put("notice", notice);
        return new Result(ResultCode.SUCCESS, params);
    }

    /**
     * 根据公司ID获取报餐设置
     *
     * @param companyId
     * @return
     */
    private MealsSetting getMealsSetting(String companyId) {
        MealsSetting mealsSetting = mealsSettingMapper.selectSettingByCompanyId(companyId);
        if (mealsSetting == null) {
            mealsSetting = mealsSettingMapper.selectSettingByCompanyId("dingcan");
        }
        return mealsSetting;
    }

    private String getEncodeInfo(String text) {
        Base64 base64 = new Base64();
        //String text = "字串文字";
        String encodedText = "";
        byte[] textByte;
        try {
            textByte = text.getBytes("UTF-8");
            //编码
            encodedText = base64.encodeToString(textByte);
            //解码
            System.out.println(new String(base64.decode(encodedText), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodedText;
    }

    private String getDecodeInfo(String text) {
        Base64 base64 = new Base64();
        String decodedText = "";
        try {
            //解码
            decodedText = new String(base64.decode(text), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return decodedText;
    }

    /**
     * 获取二维码信息
     */
    @GetMapping("/getQRCodeInfo")
    @ApiOperation("获取二维码信息")
    public Result getQRCodeInfo() {
        Map<String, Object> params = new HashMap<String, Object>();
        String encodeInfo = getEncodeInfo("dingcanxitongorgid");
        params.put("info", encodeInfo);
        return new Result(ResultCode.SUCCESS, params);
    }

    @GetMapping("/getQRCode")
    @ApiOperation("获取二维码")
    public void getQRCode(HttpServletResponse response, String text) {
        try {
            QRCodeUtil.generateQRCode(text + "." + ShiroUtils.getUser().getUserId(), 300, 300, "png", response);
        } catch (Exception e) {
            throw new UserNotFoundException();
        }
    }

    /**
     * 获取公司信息
     */
    @GetMapping("/getCompanyInfo")
    @ApiOperation("获取公司信息")
    public Result getCompanyInfo(String info) {
        JSONObject jobj = JSON.parseObject(info);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject token = (JSONObject) data.get("token");
        String orgId = token.getString("oaOrgId");
        //String companyId = token.getString("companyId");
        Company company = abutmentMapper.selectCompany(orgId);
        return new Result(ResultCode.SUCCESS, company);
    }

    /**
     * 提交公司申请信息
     */
    @GetMapping("/application")
    @ApiOperation("提交公司申请信息")
    public Result application(String info) {
        JSONObject jobj = JSON.parseObject(info);
        JSONObject data = (JSONObject) jobj.get("data");
        JSONObject companyInfo = (JSONObject) data.get("companyInfo");
        String applyArea = companyInfo.getString("applyArea");
        String orgName = companyInfo.getString("orgName");
        String applyName = companyInfo.getString("applyName");
        String applyPhone = companyInfo.getString("applyPhone");

        Company comp = new Company();
        comp.setApplyArea(applyArea);
        comp.setOrgName(orgName);
        comp.setApplyName(applyName);
        comp.setApplyPhone(applyPhone);
        comp.setStatus("2");
        abutmentMapper.insertCompany(comp);
        return new Result(ResultCode.SUCCESS);
    }


    public static void main(String[] args) {
        //String json = "{\"data\":[{\"eatDate\":\"2018-10-24\",\"dinnerType\":0,\"bookNum\":1,\"bookType\":1},{\"eatDate\":\"2018-10-24\",\"dinnerType\":1,\"bookNum\":1,\"bookType\":1}]}";

		/*JSONObject jobj = JSON.parseObject(json);
		JSONArray array = (JSONArray) jobj.get("data");
		List<Book> list = JSONObject.parseArray(array.toJSONString(), Book.class);

		System.out.println("-----====="+list);*/


		/*
		JSONObject bookListJson = (JSONObject) jobj.get("data");
		System.out.println("-----====="+bookListJson);
		String bookStr = JSON.toJSONString(bookListJson);*/
        //List<Book> bookList = JSON.parseArray(bookStr, Book.class);
        //System.out.println("-----*****"+bookList);

        //TestPerson person = JSON.parseObject("{\"name\":\"李明\",\"age\":19}", TestPerson.class);

        	/*int year = 2017;
        	int month = 2;
        	Calendar c = Calendar.getInstance();
        	c.set(year, month, 0); //输入类型为int类型

        	int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        	System.out.println(year + "年" + month + "月有" + dayOfMonth + "天");*/

		/*int y,m,d,h,mi,s;
		Calendar cal=Calendar.getInstance();
		y=cal.get(Calendar.YEAR);
		m=cal.get(Calendar.MONTH)+1;
		d=cal.get(Calendar.DATE);
		h=cal.get(Calendar.HOUR_OF_DAY);
		mi=cal.get(Calendar.MINUTE);
		s=cal.get(Calendar.SECOND);
		System.out.println("现在时刻是"+y+"年"+m+"月"+d+"日"+h+"时"+mi+"分"+s+"秒");  */

        DateFormat df = new SimpleDateFormat("HH:mm");//创建日期转换对象HH:mm:ss为时分秒，年月日为yyyy-MM-dd
        try {
            Date dt1 = df.parse("17:00");//将字符串转换为date类型
            Date dt2 = df.parse("15:20");
            if (dt1.getTime() > dt2.getTime())//比较时间大小,如果dt1大于dt2
            {
                System.out.println("yes");
            } else {
                System.out.println("no");//运行输出no
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }


    }
}
